package ccc

import (
	"fmt"
	"log"
)

// Query handles chaincode query requests.
func (fabNetworkClient *FabNetworkClient) Query(chainCodeName, channelID, function string, args []string) ([]byte, error) {
	network := fabNetworkClient.Gateway.GetNetwork(channelID)
	contract := network.GetContract(chainCodeName)
	log.Printf("EvaluateTransaction args: %v", args)
	evaluateResponse, err := contract.EvaluateTransaction(function, args...)
	if err != nil {
		return nil, err
	}
	return evaluateResponse, nil
}

// Invoke handles chaincode invoke requests.
func (fabNetworkClient *FabNetworkClient) Invoke(chainCodeName, channelID, function string, args []string) (string, error) {
	network := fabNetworkClient.Gateway.GetNetwork(channelID)
	contract := network.GetContract(chainCodeName)

	bytes, err := contract.SubmitTransaction(function, args...)
	if err != nil {
		return "", fmt.Errorf("failed to submit transaction: %w", err)
	}

	return string(bytes), err

	//txn_proposal, err := contract.NewProposal(function, client.WithArguments(args...))
	//if err != nil {
	//	return "", errors.New(fmt.Sprintf("Error creating txn proposal: %s", err))
	//}
	//txn_endorsed, err := txn_proposal.Endorse()
	//if err != nil {
	//	return "", errors.New(fmt.Sprintf("Error endorsing txn: %s", err))
	//}
	//txn_committed, err := txn_endorsed.Submit()
	//if err != nil {
	//	return "", errors.New(fmt.Sprintf("Error submitting transaction: %s", err))
	//}
	//return fmt.Sprintf("Transaction ID : %s Response: %s", txn_committed.TransactionID(), txn_endorsed.Result()), nil
}
